package com.cy.ppj.service.comm.impl;

import com.cy.ppj.dao.mapper.UniqueKeyMapper;
import com.cy.ppj.model.Result;
import com.cy.ppj.model.domian.UniqueKey;
import com.cy.ppj.model.enums.UniqueKeyType;
import com.cy.ppj.service.BaseService;
import com.cy.ppj.service.comm.UniqueKeyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @description: 唯一约束
 * @author: Ocean
 * @create: 2018-07-30 15:18
 **/
@Service
public class UniqueKeyServiceImpl extends BaseService implements UniqueKeyService {

    @Autowired
    private UniqueKeyMapper uniqueKeyMapper;

    @Override
    @Transactional
    public Result create(UniqueKeyType type, String value) {

        UniqueKey uniqueKey = new UniqueKey();
        uniqueKey.setType(type);
        uniqueKey.setValue(value);
        //查询是否存在
        int count = uniqueKeyMapper.selectCount(uniqueKey);
        if (count > 0) {
            return Result.fail("唯一约束已存在");
        }
        //保存新纪录
        uniqueKey.setCreateTime(new Date());
        uniqueKeyMapper.insertSelective(uniqueKey);
        return Result.success(null, uniqueKey.getId());
    }

    @Override
    public Result discard(UniqueKeyType type, String value) {
        UniqueKey uniqueKey = new UniqueKey();
        uniqueKey.setType(type);
        uniqueKey.setValue(value);
        uniqueKey = uniqueKeyMapper.selectOne(uniqueKey);
        if (uniqueKey == null) {
            return Result.fail("唯一约束不存在");
        }
        UniqueKey updateUniqueKey = new UniqueKey();
        updateUniqueKey.setId(uniqueKey.getId());
        updateUniqueKey.setValue(value.concat("_").concat(System.currentTimeMillis()+""));
        updateUniqueKey.setUpdateTime(new Date());
        int result = uniqueKeyMapper.updateByPrimaryKeySelective(updateUniqueKey);
        state(result == 1, "更新唯一约束异常");
        return Result.success();
    }

    @Override
    public boolean isExist(UniqueKeyType type, String value) {
        UniqueKey uniqueKey = new UniqueKey();
        uniqueKey.setType(type);
        uniqueKey.setValue(value);
        int count = uniqueKeyMapper.selectCount(uniqueKey);
        return count > 0;
    }
}
